package com.trendata.controller;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.trendata.aliyun.AliyunOSSClient;
import com.trendata.domain.Comment;
import com.trendata.domain.Image;
import com.trendata.domain.Like;
import com.trendata.domain.User;
import com.trendata.domain.socket.SocketMessage;
import com.trendata.service.CommentService;
import com.trendata.service.IServerSocketService;
import com.trendata.service.ImageService;
import com.trendata.service.LikeService;
import com.trendata.service.UserService;
import com.trendata.util.Constants;
import com.trendata.util.JsonResult;
import com.trendata.util.ResultDO;
import com.trendata.util.ReturnMsg;
import com.trendata.util.TimeUtil;

/**
 * 处理用户
 * 
 * @author: HuangXiuXiu Email:243559392@qq.com
 */
@Controller
@RequestMapping("/user")
public class UserController {

	private static Logger logger = Logger.getLogger("userLogger");

	@Autowired
	private UserService userService;
	@Autowired
	private ImageService imageService;
	@Autowired
	private LikeService likeService;
	@Autowired
	private CommentService commentService;
	@Resource
	private IServerSocketService serverSocketService;

	/**
	 * 获取当前登录用户信息
	 * <p>
	 * url=/user/getUser.do
	 * </p>
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/getUser")
	@ResponseBody
	public String getUser(HttpServletRequest request, HttpServletResponse response) {
		JsonResult result = new JsonResult();
		User user = (User) request.getSession().getAttribute(Constants.SESSION_TYPE_USER);
		request.getSession().getId();
		logger.info("user:" + user + "session　Id" + request.getSession().getId());
		result.setValue(user);
		result.setSuccess(true);
		return result.toJsonString();
	}

	/**
	 * 
	 * 获取当前登录用户图片
	 * <p>
	 * url=/user/selectUserImages.do?state=&no=&size=
	 * </p>
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/selectUserImages")
	@ResponseBody
	public String selectUserImages(HttpServletRequest request, HttpServletResponse response) {
		JsonResult result = new JsonResult();
		User user = (User) request.getSession().getAttribute(Constants.SESSION_TYPE_USER);
		String stateStr = request.getParameter("state");
		String no = request.getParameter("no");// 第几页
		String size = request.getParameter("size");// 每一页大小
		int state = Image.STATE_PRIVATE;
		if (stateStr.equals(Image.STATE_PUBLIC + "")) {
			state = Image.STATE_PUBLIC;
		}
		if (no == null || size == null) {
			return result.setMessage("请传入正确的参数").toJsonString();
		}
		int startIndex = (Integer.valueOf(no) - 1) * Integer.valueOf(size);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int totalSize = imageService.selectCountByParams(user.getOpenId(), null, state);
		resultMap.put("totalSize", totalSize);
		List<Image> userImages = imageService.selectByParamters(user.getOpenId(), null, state, startIndex, Integer.valueOf(size));
		resultMap.put("userImages", userImages);
		result.setValue(resultMap);
		result.setSuccess(true);
		return result.toJsonString();
	}

	/**
	 * 修改图片信息
	 * <p>
	 * url=/user/updateUserImages.do?imageId=&state=
	 * </p>
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/updateUserImages")
	@ResponseBody
	public String updateUserImages(HttpServletRequest request, HttpServletResponse response) {
		JsonResult result = new JsonResult();
		User user = (User) request.getSession().getAttribute(Constants.SESSION_TYPE_USER);
		String imageId = request.getParameter("imageId");
		if (imageId == null || imageId.equals("")) {
			return result.setMessage("图片编号格式错误").toJsonString();
		}
		Image image = imageService.selectById(Long.valueOf(imageId));
		if (image == null) {
			return result.setMessage("该图片不存在，请刷新！").toJsonString();
		}
		// 判断是不是本人的
		if (!image.getUserOpenId().equals(user.getOpenId())) {
			return result.setMessage("该图片不是你的").toJsonString();
		}
		String state = request.getParameter("state");
		if (state != null) {
			image.setState(Integer.valueOf(state));
		}
		imageService.update(image);
		result.setValue(image);
		result.setSuccess(true);
		return result.toJsonString();
	}

	/**
	 * 批量删除图片
	 * <p>
	 * url=/user/deleteImages.do?imageIds=1;2;3;4
	 * </p>
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/deleteImages")
	@ResponseBody
	public String deleteImages(HttpServletRequest request, HttpServletResponse response) {
		JsonResult result = new JsonResult();
		User user = (User) request.getSession().getAttribute(Constants.SESSION_TYPE_USER);
		String imageIds = request.getParameter("imageIds");
		if (imageIds == null || imageIds.equals("")) {
			return result.setMessage("图片编号格式错误").toJsonString();
		}
		try {
			String[] imageIdArray = imageIds.split(";");
			for (String id : imageIdArray) {
				Image image = imageService.selectById(Integer.valueOf(id));
				if (image == null) {
					continue;
				}
				// 判断是不是本人的
				if (!image.getUserOpenId().equals(user.getOpenId())) {
					continue;
				}
				String url = image.getUrl();
				// 删除oss上的图片
				url = url.substring(AliyunOSSClient.CDN_NAME.length());
				AliyunOSSClient.deleteObject(url);
				// 删除缩略图
				String cutUrl = url.substring(0, url.indexOf("."));
				cutUrl = cutUrl + "_cut.jpg";
				AliyunOSSClient.deleteObject(cutUrl);
				// 删除数据库的
				imageService.deleteById(image.getId());
				// 删除点赞
				likeService.deleteByImageId(image.getId());
				// 删除评论
				commentService.deleteByImageId(image.getId());
			}
		} catch (Exception e) {
			return result.setMessage("删除时出现错误，请检查传入的编号格式").toJsonString();
		}
		result.setSuccess(true);
		return result.toJsonString();
	}

	/**
	 * 插入评论
	 * <p>
	 * url=/user/insertComment.do?imageId=11&content=漂亮
	 * </p>
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/insertComment")
	@ResponseBody
	public String insertComment(HttpServletRequest request, HttpServletResponse response) {
		JsonResult result = new JsonResult();
		User user = (User) request.getSession().getAttribute(Constants.SESSION_TYPE_USER);
		String imageId = request.getParameter("imageId");
		String content = request.getParameter("content");
		if (imageId == null || imageId.equals("") || content == null || content.equals("")) {
			return result.setMessage("参数格式错误").toJsonString();
		}
		Image image = imageService.selectById(Long.valueOf(imageId));
		if (image == null) {
			return result.setMessage("该图片已经不存在了").toJsonString();
		}
		Comment comment = new Comment();
		comment.setOpenId(user.getOpenId());
		comment.setNick(user.getNickName());
		comment.setContent(content);
		comment.setImageId(Long.valueOf(imageId));
		comment.setCreateTime(TimeUtil.getCurrent());
		commentService.insert(comment);

		result.setValue(comment);
		result.setSuccess(true);
		return result.toJsonString();
	}

	/**
	 * 删除评论，可以删除自己发布的，也可以删除别人给自己的照片回复的
	 * <p>
	 * url=/user/deleteCommentById.do?commentId=2
	 * </p>
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/deleteCommentById")
	@ResponseBody
	public String deleteCommentById(HttpServletRequest request, HttpServletResponse response) {
		JsonResult result = new JsonResult();
		User user = (User) request.getSession().getAttribute(Constants.SESSION_TYPE_USER);
		String commentId = request.getParameter("commentId");
		if (commentId == null || commentId.equals("")) {
			return result.setMessage("参数格式错误").toJsonString();
		}
		Comment comment = commentService.selectById(Long.valueOf(commentId));
		if (comment != null) {
			if (!comment.getOpenId().equals(user.getOpenId())) {
				Image image = imageService.selectById(comment.getImageId());
				if (image != null && !image.getUserOpenId().equals(user.getOpenId())) {
					return result.setMessage("您无权删除").toJsonString();
				}
			}
			commentService.deleteById(comment.getId());
		}
		result.setSuccess(true);
		return result.toJsonString();
	}

	/**
	 * 用户拍照，需要先initUser.do
	 * <p>
	 * url=/user/takePhoto.do
	 * </p>
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/takePhoto")
	@ResponseBody
	public String takePhoto(HttpServletRequest request, HttpServletResponse response) {
		JsonResult result = new JsonResult();
		Long shopOpenId = (Long) request.getSession().getAttribute(Constants.SESSION_SHOP_OPEN_ID);
		User user = (User) request.getSession().getAttribute(Constants.SESSION_TYPE_USER);
		if (shopOpenId == null || shopOpenId.equals("")) {
			return result.setMessage("shopOpenId不能为空").toJsonString();
		}
		String process = SocketMessage.PROCESS_TAKE_A_PHOTO;
		ReturnMsg<String> returnMsg = serverSocketService.sendMessgaeToClientSocket(user.getOpenId(), shopOpenId + "", process);
		if (returnMsg.isSuccess()) {
			result.setValue(returnMsg.getModule());
			result.setSuccess(true);
		} else {
			result.setMessage(returnMsg.getErrMsg());
		}
		return result.toJsonString();
	}

	/**
	 * 上传base64图片
	 * <p>
	 * url=/user/savePhoto.do?base64Photo=图片base64字符串
	 * </p>
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/savePhoto")
	@ResponseBody
	public String savePhoto(HttpServletRequest request, HttpServletResponse response) {
		JsonResult result = new JsonResult();
		User user = (User) request.getSession().getAttribute(Constants.SESSION_TYPE_USER);
		Long shopOpenId = (Long) request.getSession().getAttribute(Constants.SESSION_SHOP_OPEN_ID);
		String base64Photo = request.getParameter("base64Photo");
		if (base64Photo == null || base64Photo.equals("")) {
			return result.setMessage("base64的图片参数不能为空").toJsonString();
		} else if (base64Photo.startsWith("data:image/jpeg;base64,")) {
			base64Photo = base64Photo.substring(23);
		}
		// 解析base64为图片流
		try {
			byte[] b = Base64Utils.decodeFromString(base64Photo);
			if (b != null) {
				InputStream inputStream = new ByteArrayInputStream(b);
				Calendar calendar = Calendar.getInstance();
				String key = "snapshot/users/" + user.getOpenId() + "/shareImages/shop" + shopOpenId + "/" + calendar.get(Calendar.YEAR) + "/"
						+ (calendar.get(Calendar.MONTH) + 1) + "/" + calendar.get(Calendar.DAY_OF_MONTH) + "/" + new java.util.Date().getTime();
				String cutKey = key + "_cut.jpg";
				key = key + ".jpg";
				ObjectMetadata objectMetadata = new ObjectMetadata();
				objectMetadata.setContentType("image/jpeg");
				objectMetadata.setContentEncoding("utf-8");
				objectMetadata.setContentLength(inputStream.available());
				// 上传至oss
				ResultDO<String> resultDO = AliyunOSSClient.putObject(key, inputStream, objectMetadata);
				if (resultDO.isSuccess()) {
					String imgUrl = resultDO.getModule();
					// 存储图片地址到数据库
					Image image = new Image();
					image.setUserOpenId(user.getOpenId());
					image.setShopOpenId(shopOpenId);
					image.setUrl(imgUrl);
					image.setState(Image.STATE_SHOW);
					image.setCreateTime(TimeUtil.getCurrent());
					imageService.insert(image);
					result.setValue(image);
					HttpURLConnection httpURLConnection = AliyunOSSClient.callImgService(key, Constants.IMAGE_TRANSFORM);
					objectMetadata.setContentLength(httpURLConnection.getContentLengthLong());
					objectMetadata.setContentType(httpURLConnection.getContentType());
					objectMetadata.setContentEncoding("utf-8");
					resultDO = AliyunOSSClient.putObject(key, httpURLConnection.getInputStream(), objectMetadata);
					if (!resultDO.isSuccess()) {
						result.setMessage("压缩图片时出现错误");
						logger.error(result.getMessage());
					}
					// 生成一张缩略图
					httpURLConnection = AliyunOSSClient.callImgService(key, Constants.CUT_IMAGE_TRANSFORM);
					objectMetadata.setContentLength(httpURLConnection.getContentLengthLong());
					objectMetadata.setContentType(httpURLConnection.getContentType());
					objectMetadata.setContentEncoding("utf-8");
					resultDO = AliyunOSSClient.putObject(cutKey, httpURLConnection.getInputStream(), objectMetadata);
					if (!resultDO.isSuccess()) {
						result.setMessage("生成缩略图时出现错误");
						logger.error(result.getMessage());
					}
					httpURLConnection.disconnect();
					result.setSuccess(true);
					return result.toJsonString();
				}
			}
		} catch (Exception e) {
			result.setMessage("处理图片时出现异常:" + e.getMessage());
			logger.error(result.getMessage());
		}
		return result.toJsonString();
	}

	/**
	 * 点赞
	 * <p>
	 * url=/user/insertLike.do?imageId=1
	 * </p>
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/insertLike")
	@ResponseBody
	public String insertLike(HttpServletRequest request, HttpServletResponse response) {
		JsonResult result = new JsonResult();
		User user = (User) request.getSession().getAttribute(Constants.SESSION_TYPE_USER);
		if (user == null) {
			return result.setMessage("请先登录").toJsonString();
		}
		String imageId = request.getParameter("imageId");
		if (imageId == null || imageId.equals("")) {
			return result.setMessage("参数错误").toJsonString();
		}
		Like like = new Like();
		like.setImageId(Long.valueOf(imageId));
		like.setUserOpenId(user.getOpenId());
		like.setCreateTime(TimeUtil.getCurrent());
		likeService.insert(like);
		result.setValue(like);
		result.setSuccess(true);
		return result.toJsonString();
	}

	/**
	 * 删除图片点赞
	 * <p>
	 * url=/user/deleteLikeByImageId.do?imageId=图片的编号
	 * </p>
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/deleteLikeByImageId")
	@ResponseBody
	public String deleteLikeById(HttpServletRequest request, HttpServletResponse response) {
		JsonResult result = new JsonResult();
		User user = (User) request.getSession().getAttribute(Constants.SESSION_TYPE_USER);
		if (user == null) {
			return result.setMessage("请先登录").toJsonString();
		}
		String imageId = request.getParameter("imageId");
		if (imageId == null || imageId.equals("")) {
			return result.setMessage("缺少参数").toJsonString();
		}
		Like like = likeService.selectByImageIdAndUserOpenId(Long.valueOf(imageId), user.getOpenId());
		if (like != null) {
			likeService.deleteById(like.getId());
			result.setSuccess(true);
		} else {
			result.setMessage("您没有对该图片点过赞");
		}

		return result.toJsonString();
	}
}
